
var Customers = new Class({
    Implements: Options,
    options: {
        'tagid':'',
        'showCalendar':false
    },
    initialize: function(opts) {
        this.setOptions(opts);

        this.panel = document.id(this.options.tagid);
        if(!this.panel) return;
        this.panel.empty();

        this.begDate = this.endDate = new Date().format('%Y-%m-%d');
        this.content = '';
        this.listData = '';
        this.curPage = 0;
        this.calendar = function(){};
        this.pager = function(){};

        this.createCustomersTable();

        this.custRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Loading...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data;
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err){alert('Error...\n' + err);return;}
                new Loader().hide();

                this.fillContent(data);
            }.bind(this)
        }).send('table=custs&beg=' + this.begDate + '&end=' + this.endDate  + '&nc=' + Date.now());

    },
    createCustomersTable: function() {
        this.content = new Element('div#content');
        this.listData = new Element('table#listData', {'rules':'groups'});

        this.panel.adopt(
            new Element('div#legend', { html:
                '<b>Legend:</b>&nbsp;<tt style="background-color:#7bcf7b;">&nbsp;import;&nbsp;</tt>&nbsp;&nbsp;&nbsp;' +
                '<i><b>A</b> - cws, <b>B</b> - bizrate, <b>F</b> - froogle, <b>G</b> - pricegrabber,' +
                '<b>H</b> - bing, <b>J</b> - cj, <b>M</b> - cwm, <b>N</b> - nexttag, <b>O</b> - onetime,' +
                '<b>S</b> - shopping, <b>L</b> - links</i>'
            }),
            new Element('div.tl[html=<div class="tr"><div>&nbsp;</div></div>]'),
            this.content.adopt(this.listData),
            new Element('div.bl[html=<div class="br"><div>&nbsp;</div></div>]')
        )

        // create calendar and pager
        var calendar = new Element('td.left');
        var pager = new Element('td.right');
        new Element('table#pager').adopt(
            new Element('tbody').adopt(
                new Element('tr').adopt(
                    calendar,
                    pager
                )
            )
        ).inject(this.content, 'top');

        this.calendar = new Calendar({
            'tagid': calendar,
            onSelect: function(bedDate, endDate) {
                this.begDate = bedDate;
                this.endDate = endDate;
                this.curPage = 0;

                this.custRequest.send('table=custs&curPage=0&beg=' + this.begDate + '&end=' + this.endDate + '&nc=' + Date.now());
            }.bind(this)
        });

        this.pager = new Pager({
            'tagid': pager,
            onNewpage: function(currentPage) {
                this.curPage = currentPage;

                this.custRequest.send('table=custs&beg=' + this.begDate + '&end=' + this.endDate + '&curPage=' + this.curPage + '&nc=' + Date.now());
            }.bind(this)
        });

        this.createHead();
    },
    createHead: function() {
        this.listData.adopt(
            new Element('thead').adopt(
                new Element('tr').adopt(
                    new Element('th.brdCol.w15[html=&nbsp;]'),
                    new Element('th.brdCol.w80[text=Time]'),
                    new Element('th#srchead.brdCol.w80[text=No]').store('tbname','no'),
                    new Element('th#srchead.brdCol.w80[text=AccwareAccount]').store('tbname','accware'),
                    new Element('th.brdCol.w120[text=Name]'),
                    new Element('th#srchead.brdCol.w120[text=Email]').store('tbname','email'),
                    new Element('th.brdCol.w50[text=Orders]'),
                    new Element('th.brdCol.w50[text=Amount]')
                )
            ),
            new Element('tfoot').adopt(
                new Element('tr').adopt(
                    new Element('th.tdFull[html=&nbsp;][colspan=8]')
                )
            ),
            new Element('tbody')
        );

        new Suggest({'url': '/Admin/webstat/getFromMySQL',
            'tagid': this.options.tagid,
            'table': 'sugcust',
            'minLength':1,
            onChoice: function(custid) {

                this.custRequest.send('table=custs&custid=' + custid + '&nc=' + Date.now());
            }.bind(this)
        });

    },
    fillContent: function(data) {
        this.pager.setData(this.curPage, data.cntPage, data.onPage, data.rows.length);

        var tbody,order,tr,td,color=false,date,dparse;

        tbody = this.listData.getElement('tbody');
        tbody.empty();

        var tagid;
        for(var i = 0; i < data.rows.length; i++) {
            order = data.rows[i];

            // set tr date
            dparse = Date.parse(order.date).format('%m%d%Y');
            if(date != dparse) {
                date = dparse;

                tbody.adopt(
                    new Element('tr').adopt(
                        new Element('td.trdate[text=' + Date.parse(order.date).format('%a %b %d %Y') + ']', {'colspan':8})
                    )
                )
            }

            tr = new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]',{
                'events': {
                    'mouseenter': function() {this.addClass('rowHover');},
                    'mouseleave': function() {this.removeClass('rowHover');}
                }
            });

            tagid = 'ord_' + i;
            td = new Element('td.imgCol').adopt(
                new Element('a.' + (order.orders ? 'plus' : 'disalow') +'[href=javascript:;][html=&nbsp;][title=Open order]',{
                    'events': {
                        'click': order.orders ? this.getOrders.bind(this, order.id, tagid) : function(){},
                        'focus': function() {this.blur();}
                    }
                })
            );

            tbody.adopt(
                tr.adopt(
                    td,
                    new Element('td.brdCol.center.w80[text=' + Date.parse(order.date).format('%H:%M:%S %a') + ']'),
                    new Element('td.brdCol.center.w80[text=' + order.no + ']'),
                    new Element('td.brdCol.center.w80[text=' + order.accw + ']'),
                    new Element('td.brdCol.w150[text=' + order.name + ']'),
                    new Element('td.brdCol.w150' + (order.resl ? '.green' : '') + '[text=' + order.email + ']'),
                    new Element('td.brdCol.right.w50[text=' + (order.orders ? order.orders : '') + ']'),
                    new Element('td.brdCol.right.w50[text=' + (order.amount ? '$' + numberFormat(order.amount) : '') + ']')
                )
            );

            if(order.orders) {
                tr = new Element('tr#x' + tagid + '[style=display:none;]').adopt(
                    new Element('td[html=&nbsp;]'),
                    new Element('td#d' + tagid + '[colspan=7][style=padding-top:0]')
                )
                tbody.adopt(tr);
            }
        } // for
        this.listData.adopt(tbody);

    },
    getOrders: function(custid, tagid, ev) {
        ev.stop();
        this.curOrdersPage = 0;

        var xcuc = document.id('x' + tagid);
        var dcuc = document.id('d' + tagid);
        if(ev.target.hasClass('plus')) {
            ev.target.removeClass('plus').addClass('minus');

            dcuc.empty();

            var calendar = new Element('td.left');
            var pager = new Element('td.right');
            new Element('table#pager').adopt(
                new Element('tbody').adopt(
                    new Element('tr').adopt(
                        calendar,
                        pager
                    )
                )
            ).inject(dcuc, 'top');

            this.ordersPager = new Pager({
                'tagid': pager,
                onNewpage: function(currentPage) {
                    this.curOrdersPage = currentPage;

                    this.ordersRequest.send('table=custorders&cid=' + custid + '&curPage=' + this.curOrdersPage + '&nc=' + Date.now());
                }.bind(this)
            });

            var table = new Element('table#listOrder').adopt(
                new Element('thead').adopt(
                    new Element('tr', { html:
                        '<th class="brdCol w15>&nbsp;</th>' +
                        '<th class="brdCol w80>Time</th>' +
                        '<th class="brdCol w80>No</th>' +
                        '<th class="brdCol w50>COD</th>' +
                        '<th class="brdCol w50>Wnty</th>' +
                        '<th class="brdCol w50>Ship Price</th>' +
                        '<th class="brdCol w50>Ship Method</th>' +
                        '<th class="brdCol w50>Tax</th>' +
                        '<th class="brdCol w50>Amount</th>'
                    })
                ),
                new Element('tfoot').adopt(
                    new Element('tr').adopt(
                        new Element('th.tdFull[html=&nbsp;]', {'colspan':9})
                    )
                ),
                new Element('tbody')
            ).inject(dcuc);

            this.ordersRequest = new Request({
                url: '/Admin/webstat/getFromMySQL',
                method: 'get',
                onRequest: function() {
                    ev.target.toggleClass('load');
                },
                onComplete: function(resp) {
                    var data;
                    try {
                        data = eval('(' + resp + ')');
                    }
                    catch(err){alert('Error...' + err);return;}
                    ev.target.toggleClass('load');

                    this.ordersContent(data, table);
                }.bind(this)
            }).send('table=custorders&cid=' + custid + '&nc=' + Date.now());

            xcuc.set('styles', {'display':'','background-color':'#ffffff'});
        }
        else {
            ev.target.removeClass('minus').addClass('plus');

            xcuc.setStyle('display', 'none');
        }
    },
    ordersContent: function(data, table) {

        this.ordersPager.setData(data.curPage, data.cntPage, data.onPage, data.rows.length);

        var tbody,order,tr,td,color=true;

        tbody = table.getElement('tbody');
        tbody.empty();

        for(var i = 0; i < data.rows.length; i++) {
            order = data.rows[i];

            tr = new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]',{
                'events': {
                    'mouseenter': function() {this.addClass('rowHover');},
                    'mouseleave': function() {this.removeClass('rowHover');}
                }
            });

            td = new Element('td.imgCol').adopt(
                new Element('a.open[href=javascript:;][html=&nbsp;][title=Show Order]',{
                    'events': {
                        'click': this.getOrder.bind(this, order.id),
                        'focus': function() {this.blur();}
                    }
                })
            );

            tbody.adopt(
                tr.adopt(
                    td,
                    new Element('td.brdCol.center.w80[text=' + Date.parse(order.date).format('%b %d,%Y %H:%M:%S %a') + ']'),
                    new Element('td.brdCol.right.w80[text=' + order.no + ']'),
                    new Element('td.brdCol.center.w50[text=' + (order.cod == 'Y' ? 'Y' : '') + ']'),
                    new Element('td.brdCol.center.w50[text=' + (order.wty == 'Y' ? 'Y' : '') + ']'),
                    new Element('td.brdCol.right.w50[text=$' + numberFormat(order.sh_pr) + ']'),
                    new Element('td.brdCol.center.w50[text=' + order.sh_md + ']'),
                    new Element('td.brdCol.right.w50[text=' + (order.tax ? '$' + numberFormat(order.tax) : '') + ']'),
                    new Element('td.brdCol.right.w50[text=$' + numberFormat(order.amount) + ']')
                )
            );
        }// for

    },
    getOrder: function(orderid, ev) {
        ev.stop();
        new ShowOrder(orderid, ev.target);
    }
});

